<template>
  <div class="user">
    <!-- 内容区域 -->
    <el-card>
      <!-- 搜索重置 -->
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="username"
            placeholder="请输入..."
            style="width: 280px;"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUserList" class="search"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="reSet">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        class="el-icon-edit adduser"
        @click="addUsers = true"
        >新增用户</el-button
      >
      <el-alert :title="`共${counts}条记录`" type="info" show-icon> </el-alert>
      <el-table :data="userlist" border stripe class="table">
        <el-table-column label="序号" prop="id" width="70px"></el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
          width="140px"
        ></el-table-column>
        <el-table-column
          label="联系电话"
          prop="phone"
          width="130px"
        ></el-table-column>
        <el-table-column
          label="用户名"
          prop="username"
          width="130px"
        ></el-table-column>
        <el-table-column
          label="权限组名称"
          prop="permission_group_title"
          width="130px"
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="role"
          width="130px"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleUser(scope.row.id)"
              >删除</el-button
            ></template
          >
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 8, 10, 20]"
          :page-size="pagesize"
          layout="sizes, prev, pager, next, jumper"
          :total="counts"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 新增用户对话框 -->
    <el-dialog
      title="创建用户"
      :visible.sync="addUsers"
      @close="addDialogClosed"
    >
      <el-form
        label-width="150px"
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            autocomplete="off"
            style="width:350px"
            v-model="addForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            autocomplete="off"
            style="width:350px"
            v-model="addForm.email"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            autocomplete="off"
            style="width:350px"
            v-model="addForm.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input
            autocomplete="off"
            style="width:350px"
            v-model="addForm.role"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限组名称" prop="permission_group_id">
          <el-select
            placeholder="请选择"
            style="width:350px"
            v-model="addForm.permission_group_id"
          >
            <el-option label="超级管理员" :value="1"></el-option>
            <el-option label="编辑组" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            autocomplete="off"
            style="width:350px"
            v-model="addForm.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="introduction">
          <el-input
            v-model="addForm.introduction"
            type="textarea"
            style="width:350px"
            placeholder="Please input"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUsers = false">取 消</el-button>
        <el-button type="primary" @click="adUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      @close="editDialogClosed"
    >
      <el-form
        label-width="150px"
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
      >
        <el-form-item label="用户名">
          <el-input
            autocomplete="off"
            style="width:350px"
            v-model="editForm.username"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            autocomplete="off"
            style="width:350px"
            v-model="editForm.email"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input
            autocomplete="off"
            style="width:350px"
            v-model="editForm.role"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限组名称" prop="permission_group_id">
          <el-select
            placeholder="请选择"
            style="width:350px"
            v-model="editForm.permission_group_id"
          >
            <el-option label="超级管理员" :value="1"></el-option>
            <el-option label="编辑组" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            autocomplete="off"
            style="width:350px"
            v-model="editForm.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="introduction">
          <el-input
            v-model="editForm.introduction"
            type="textarea"
            style="width:350px"
            placeholder="Please input"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="putUsers">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { user, addUser, idUser, dellUser, putUser } from "@/api/base";
export default {
  name: "User",
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    // 验证手机号的规则
    const checkPhone = (rule, value, cb) => {
      const regPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regPhone.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机"));
    };
    return {
      page: 1,
      pagesize: 5,
      username: "",
      userlist: [],
      addUsers: false,
      editDialogVisible: false,
      editForm: {},
      counts: 0,
      addForm: {
        avatar: "",
        username: "",
        password: "",
        email: "",
        phone: "",
        role: "",
        permission_group_id: [1 || 2],
        introduction: "",
      },
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在 3 到 10 个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码的长度在 6 到 15个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        phonephonephone: [
          { required: true, message: "请输入手机", trigger: "blur" },
          {
            validator: checkPhone,
            trigger: "blur",
          },
        ],
      },
      editFormRules: {
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码的长度在 6 到 15个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机", trigger: "blur" },
          {
            validator: checkPhone,
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data } = await user({
        page: this.page,
        pagesize: this.pagesize,
        username: this.username,
      });
      this.userlist = data.list;
      this.counts = data.counts;
    },
    reSet() {
      this.username = "";
    },
    // 确定校验并添加请求
    adUser() {
      try {
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) return;
          const { data } = await addUser(this.addForm);
          this.addUsers = false;
          this.getUserList();
        });
        this.$message.success("添加成功");
      } catch (err) {
        this.$message.error("添加失败");
      }
    },
    putUsers() {
      try {
        this.$refs.editFormRef.validate(async (valid) => {
          if (!valid) return;
          const { data } = await putUser(this.editForm.id, {
            avatar: "",
            username: this.editForm.username,
            password: this.editForm.password,
            email: this.editForm.email,
            phone: this.editForm.phone,
            role: this.editForm.role,
            permission_group_id: this.editForm.permission_group_id,
            introduction: this.editForm.introduction,
          });
          this.editDialogVisible = false;
          this.getUserList();
          this.$message.success("编辑成功");
        });
      } catch (err) {
        this.$message.error("编辑失败");
      }
    },
    // id获取
    async showEditDialog(id) {
      try {
        const { data } = await idUser(id);
        this.editForm = data;
        this.editDialogVisible = true;
        this.$message.success("获取成功");
      } catch (err) {
        this.$message.error("获取失败");
      }
    },
    // 删除请求
    async deleUser(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }

      try {
        const { data } = await dellUser(id);
        this.getUserList();
        this.$message.success("删除成功");
      } catch (err) {
        this.$message.error("删除失败");
      }
    },
    handleSizeChange(newSize) {
      this.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.page = newPage;
      this.getUserList();
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
  },
};
</script>
<style lang="less" scope>
.user {
  position: relative;
  .search {
    margin-left: -24px;
    margin-bottom: 20px;
  }
  .adduser {
    position: absolute;
    right: 42px;
    top: 60px;
    z-index: 2222;
  }
  .table {
    margin-top: 10px;
  }
  .block {
    margin-top: 5px;
  }
  .el-dialog {
    border-radius: 10px;
    .el-dialog__header {
      background-color: rgb(64, 158, 255);
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
      .el-dialog__title {
        color: #fff;
      }
    }
  }
  .el-card {
    margin: 20px;
    min-width: 900px;
  }
}
</style>
